import java.util.Random;

/**
 * This class makes the decide of the cell according to the rule of the
 * automaton
 * 
 * @author root
 *
 */

public class RulesEngine {

	protected TreeCell currentCell;
	protected TreeCell upCell;
	protected TreeCell downCell;
	protected TreeCell rightCell;
	protected TreeCell leftCell;
	protected double p_growNewPlantProb;
	protected double g_combustibilityProb;
	protected double f_lightningStrikeProb;


	/**
	 * decide the state of the cell according to its neighbors
	 * 
	 * @param currentCell
	 * @param upCell
	 * @param downCell
	 * @param rightCell
	 * @param leftCell
	 * @param p_growNewPlantProb
	 * @param g_combustibilityProb
	 * @param f_lightningStrikeProb
	 * @param s_neighborSeedingProb
	 */
	public void decideCellState(TreeCell currentCell, TreeCell upCell,
			TreeCell downCell, TreeCell rightCell, TreeCell leftCell,
			double p_growNewPlantProb, double g_combustibilityProb,
			double f_lightningStrikeProb) {
		this.currentCell= currentCell;
		this.upCell = upCell;
		this.downCell= downCell;
		this.rightCell=rightCell;
		this.leftCell=leftCell;
		
		this.p_growNewPlantProb=p_growNewPlantProb;
		this.g_combustibilityProb=g_combustibilityProb;
		this.f_lightningStrikeProb=f_lightningStrikeProb;
		
		
		switch (currentCell.cellState) {
		case TreeCell.EMPTY_CELL:
			handleEmptyCell();
			break;
		case TreeCell.TREE_CELL:
			handleTreeCell();
			break;
		case TreeCell.BURNING_TREE_CELL:
			handleBurningCell();
			break;	
		}
	}

	
	protected void handleEmptyCell() {
		if (decideWithProbability(p_growNewPlantProb) )
		  currentCell.cellState=TreeCell.TREE_CELL;
	}
	protected void handleBurningCell() {
		currentCell.cellState=TreeCell.EMPTY_CELL;
	}

	protected void handleTreeCell() {
		if ((upCell.cellState==TreeCell.BURNING_TREE_CELL||
				downCell.cellState==TreeCell.BURNING_TREE_CELL||
				rightCell.cellState==TreeCell.BURNING_TREE_CELL||	
				leftCell.cellState==TreeCell.BURNING_TREE_CELL) &&
				decideWithProbability(g_combustibilityProb))
					currentCell.cellState=TreeCell.BURNING_TREE_CELL;
		else{
			if (decideWithProbability(f_lightningStrikeProb))
				currentCell.cellState=TreeCell.BURNING_TREE_CELL;
		}
	}
	
	private static Random rand = new Random();
	/**
	 * This method returns true with a given probability 
	 * 
	 * @param trueProb
	 * @return
	 */
	public static boolean decideWithProbability(double trueProb){
		if (rand.nextDouble()< trueProb)
			return true;
		return false;
	}


	
}
